package org.eva.hydra.redis.service;

import org.eva.hydra.redis.domain.DemoInfo;
import org.eva.hydra.redis.repository.DemoInfoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import static org.springframework.data.jpa.domain.AbstractPersistable_.id;

/**
 * http://412887952-qq- 1.38 （35）Spring Boot集成Redis实现缓存机制【从零开始学Spring
 * Boot】
 * 第 177 / 266 页
 * <p>
 * DemoInfo数据处理类
 * *
 *
 * @author Angel(QQ:412887952)
 * @version v.0.1
 */
@Service
public class DemoInfoService {
    @Resource
    private DemoInfoRepository demoInfoRepository;
    @Resource
    private RedisTemplate<String, String> redisTemplate;

//    private RedisTemplate redisTemplate;
//
//    @Autowired(required = false)
//    public void setRedisTemplate(RedisTemplate redisTemplate) {
//        RedisSerializer stringSerializer = new StringRedisSerializer();
//        redisTemplate.setKeySerializer(stringSerializer);
//        redisTemplate.setValueSerializer(stringSerializer);
//        redisTemplate.setHashKeySerializer(stringSerializer);
//        redisTemplate.setHashValueSerializer(stringSerializer);
//        this.redisTemplate = redisTemplate;
//    }

    public void test() {
        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
        valueOperations.set("mykey4", "random1=" + Math.random());
        System.out.println(valueOperations.get("mykey4"));
    }

    //keyGenerator="myKeyGenerator"
    @Cacheable(value = "demoInfo") //缓存,这里没有指定key.
    public DemoInfo findById(String id) {
        System.err.println("DemoInfoServiceImpl.findById()=========从数据库中进行获取的....id=" + id);
        return demoInfoRepository.findOne(id);
    }

    @CacheEvict(value = "demoInfo")
    public void deleteFromCache(String id) {
        System.out.println("DemoInfoServiceImpl.delete().从缓存中删除.");
    }
}
